import React, { useRef, useState } from "react";
import { ProTable, ProColumnType } from "@ant-design/pro-components";
import { weightRatioTypes } from "@/constants/types";
import { Button, Modal, Space, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { fetchBaseWeightRatioList, baseWeightRatioAdd, baseWeightRatioDelete, baseWeightRatioUpdate } from "../services";
import { useRequest } from "ahooks";
import WeightRatioUpdate from "../modals/WeightRatioUpdate";
import { useModel } from "@umijs/max";


const WeightRatio = () => {
  const tableRef = useRef();
  const [visible, setVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<weightRatioTypes | null>(null);
  const {loading: addLoading, runAsync: addApi} = useRequest(baseWeightRatioAdd, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(baseWeightRatioUpdate, {manual: true});
  const { getDict } = useModel('dictModel');
  const countrys = getDict('country');
  const prdTypes = getDict('prdType');
  

  const columns: ProColumnType<weightRatioTypes> [] = [
    {
      title: '国家',
      dataIndex: 'country',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: countrys
      }
    },
    {
      title: '产品',
      dataIndex: 'product',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: prdTypes
      }
    },
    {
      title: '国家',
      dataIndex: 'countryName',
      search: false
    },
    {
      title: '产品',
      dataIndex: 'productName',
      search: false
    },
    {
      title: '货重比',
      dataIndex: 'leftRatio',
      search: false,
      render: (_, record: weightRatioTypes) => (
        <Space>
          <span>{record?.leftRatio || ''}</span>，
          <span>{record?.rightRatio || ''}</span>
        </Space>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      search: false
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      render: (_, record: weightRatioTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleDel(record)}>删除</Button>
          </Space>
        )
      }
    },
  ];

  const weightRatioUpdateProps = {
    visible,
    loading: addLoading || updateLoading,
    currentRow,
    title: currentRow ? '编辑货重比': '新建货重比',
    onCancel: () => {
      setCurrentRow(null);
      setVisible(false);
    },
    onSubmit: async (params: weightRatioTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        weightRatioUpdateProps.onCancel();
        tableRef?.current?.reload();
      }
    }
  }
  const handleAdd = () => {
    setVisible(true);
  }
  const handleEdit = (record: weightRatioTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  const handleDel = (record: weightRatioTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定删除？',
      onOk: () => {
        baseWeightRatioDelete({id: record.id}).then(res => {
          tableRef?.current?.reload();
        })
      }
    });
  }

  return (
    <> 
      <ProTable
        actionRef={tableRef}
        bordered
        rowKey="id"
        options={false}
        columns={columns}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          params.pageNum = params.current;
          const res = await fetchBaseWeightRatioList({
            ...params,
            pageNum: params.current || 1,
            pageSize: params.pageSize || 20,
          });
          return {
            data: res.data || [],
            total: res.total || 0,
            success: true
          }
        }}
        pagination={{
          pageSize: 10
        }}
        toolBarRender={() => [
          <Button key="create" onClick={handleAdd} type="primary">
            <PlusOutlined />
            新建货重比
          </Button>
        ]}
      />
      {visible && <WeightRatioUpdate {...weightRatioUpdateProps} />}
    </>
  );
}
export default WeightRatio;